// BuildTools.cs
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Collections.Generic;

public class BuildTools
{
    [MenuItem("Build/Build APK")]
    public static void BuildApk()
    {

        Debug.Log("执行BuildApk");
        // 解析命令行参数
        string[] args = System.Environment.GetCommandLineArgs();
        bool isApk = false;
        bool isDebug = false;
        foreach (var s in args)
        {
            Debug.Log(s);
            if (s.Contains("--GameName:"))
            {
                string gameName = s.Split(':')[1];
                // 设置app名字
                Debug.Log("GameName --:" + gameName);
                PlayerSettings.productName = gameName;
            }

            if (s.Contains("--GameVersion:"))
            {
              
                string version = s.Split(':')[1];
                Debug.Log("GameVersion --:" + version);
                // 设置版本号
                PlayerSettings.bundleVersion = version;
            }

            if (s.Contains("--Type:"))
            {
                string type = s.Split(':')[1];
                if(type == "普通Apk包"){
                    EditorUserBuildSettings.exportAsGoogleAndroidProject = false;
                    EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
                    isApk = true;
                }else{
                    EditorUserBuildSettings.exportAsGoogleAndroidProject = true;
                    EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
                }
                Debug.Log("Type --:" + type);
            }


            if (s.Contains("--ANDROID_SDK="))
            {
                string androidSDKPath = s.Split('=')[1];
                Debug.Log("ANDROID_SDK --:" + androidSDKPath);
                UpdateSetting("AndroidSdkRoot", "ANDROID_SDK", androidSDKPath, "");
              
            }

            if (s.Contains("--ANDROID_NDK="))
            {
                string androidNdkPath = s.Split('=')[1];
                Debug.Log("ANDROID_NDK --:" + androidNdkPath);
                UpdateSetting("AndroidNdkRoot", "ANDROID_NDK", androidNdkPath, "");
              
            }

            if (s.Contains("--JAVA_SDK="))
            {
                string jdkPath = s.Split('=')[1];
                Debug.Log("JAVA_SDK --:" + jdkPath);
                UpdateSetting("JdkPath", "JAVA_SDK", jdkPath, "");
              
            }


            if (s.Contains("--keystore="))
            {
                string keyName = s.Split('=')[1];

                PlayerSettings.Android.keystoreName = keyName;
        
                PlayerSettings.Android.keystorePass = "123456";
                PlayerSettings.Android.keyaliasName = "key";
                PlayerSettings.Android.keyaliasPass = "123456";

            }

            if (s.Contains("--ScriptingBackend="))
            {
                string scriptingBackend = s.Split('=')[1];

                if(scriptingBackend == "调试包"){
                    isDebug = true;
                }else{
                    isDebug = false;
                }
         
               

            }
        }

        PlayerSettings.allowUnsafeCode = true;

     
       
        PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android,ScriptingImplementation.IL2CPP);
        PlayerSettings.SetApiCompatibilityLevel(BuildTargetGroup.Android,ApiCompatibilityLevel.NET_4_6); 
        PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARM64 | AndroidArchitecture.ARMv7;
        PlayerSettings.defaultInterfaceOrientation = UIOrientation.AutoRotation;

        PlayerSettings.allowedAutorotateToLandscapeRight = true;
        PlayerSettings.allowedAutorotateToLandscapeLeft = true;
        PlayerSettings.allowedAutorotateToPortrait = false;
        PlayerSettings.allowedAutorotateToPortraitUpsideDown = false;
        EditorUserBuildSettings.androidBuildSubtarget = MobileTextureSubtarget.ASTC;
     
        #if UNITY_ANDROID 
            Debug.Log("Build UNITY_ANDROID !");
        #else
            Debug.Log("切换平台 UNITY_ANDROID !");
            EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Android,BuildTarget.Android);
        #endif
        Debug.Log("Build App Done!");

        //打包ab 资源
        SetBundles.CopyLua();
        BuildBundles.Build();
        
        //拷贝到指定文件夹
        //清理 streamingAssetsPath
    
        string assetBundlePath = Application.streamingAssetsPath + "/Assetbundles";
        DirectoryInfo dirInfo2 = new DirectoryInfo(assetBundlePath);
        if(dirInfo2.Exists){
            dirInfo2.Delete(true);
            //拷贝到 指定文件夹
            dirInfo2.Create();   
        }
        string outputPath = Path.Combine(BuildBundles.OUT_PATH, EditorPlatform.GetPlatformName());
        CopyFolder(BuildBundles.OUT_PATH,assetBundlePath);
        DirectoryInfo Bin = new DirectoryInfo( Application.dataPath + "/../Bin/");
		if(Bin.Exists){
			Bin.Delete(true);
		}
        // 执行打包
        BuildPlayerOptions opt = new BuildPlayerOptions();
        opt.scenes = new string[] { "Assets/App/ttddz/Scenes/Launch.unity" };
   
        if(isApk){
            opt.locationPathName =  Application.dataPath + "/../Bin/test.apk";
        }else{
            opt.locationPathName =  Application.dataPath + "/../Bin/test";
          
        }

       
        opt.target = BuildTarget.Android;
        if(isDebug){
            opt.options = BuildOptions.Development|BuildOptions.ConnectWithProfiler;
        }else{
            opt.options = BuildOptions.None;
        }
     
        BuildPipeline.BuildPlayer(opt);
	   

       
        //对应拷贝资源到指定文件夹内
        if(!isApk){
            //
            string srcPath =  opt.locationPathName  + "/unityLibrary/src/main/assets/";
            DirectoryInfo directoryInfo = new DirectoryInfo(srcPath);
            string parentPath = Application.dataPath + "/../svnNeedPath/";
            DirectoryInfo parentPathInfo = new DirectoryInfo(parentPath);
            if(parentPathInfo.Exists){
               parentPathInfo.Delete(true);
            }
            Directory.CreateDirectory(parentPath);
            string tagPath = Application.dataPath + "/../svnNeedPath/assets/";
            if(!Directory.Exists(tagPath)){
                Directory.CreateDirectory(tagPath);
            }

            if(directoryInfo.Exists){
                CopyFolder(srcPath,tagPath);
            }

            string libSrcPath =  opt.locationPathName +  "/unityLibrary/src/main/jniLibs/";
            DirectoryInfo libdirectoryInfo = new DirectoryInfo(libSrcPath);
            string libTagPath = Application.dataPath + "/../svnNeedPath/lib/";

            if(!Directory.Exists(libTagPath)){
                Directory.CreateDirectory(libTagPath);
            }

            if(libdirectoryInfo.Exists){
                CopyFolder(libSrcPath,libTagPath);
            }
        }

    }

    /// <summary>
	/// 移动文件夹
	/// </summary>
	/// <param name="oldPath">原始文件夹路径</param>
	/// <param name="newPath">目标文件路径</param>
	public static void MoveDirectory(string oldPath,string newPath){
		string[] files = Directory.GetFiles(oldPath, "*.*", SearchOption.AllDirectories);

		DirectoryInfo assetsPath = new DirectoryInfo(newPath);
		if (assetsPath.Exists == false){
			Directory.CreateDirectory(newPath);
		}

		string tempStr1 = "";
		string tempStr3 = "";
		bool haveSVN = false;//是否有SVN 文件
		foreach (string file in files)
		{
			if(!file.Contains(".svn")){
				FileInfo mFile = new FileInfo(file);

				//加工 路径
				tempStr1 = file.Replace(oldPath,"");
				tempStr1 = tempStr1.Replace(mFile.Name,"");
				//最终文件路径
				tempStr3 = newPath + tempStr1;
				//判断是否是文件夹,如果是文件夹则创建
				FileInfo fi = new FileInfo(tempStr3);
				if((fi.Attributes & FileAttributes.Directory) != 0){
					if (!Directory.Exists(tempStr3)){
						DirectoryInfo directoryInfo = new DirectoryInfo(tempStr3);
						directoryInfo.Create();
					}
				}

				if (new FileInfo(tempStr3).Exists == false) 
				{
					if(new FileInfo(tempStr3 + mFile.Name).Exists == true){
						File.Delete(tempStr3 + mFile.Name);
					}
					mFile.MoveTo(tempStr3 + mFile.Name);
				}else{
					File.Delete(tempStr3);
					mFile.MoveTo(tempStr3 + mFile.Name);
				}
			}else{
				haveSVN = true;
			}
		}
		
		//删除空 文件夹()
		if(haveSVN){
			string[] files2 = Directory.GetFiles(oldPath, "*.*", SearchOption.TopDirectoryOnly);
			foreach (string file in files2)
			{
				if(!file.Contains(".svn")){
					//判断是否是文件夹,如果是文件夹则创建
					FileInfo fi = new FileInfo(file);
					if((fi.Attributes & FileAttributes.Directory) != 0){
						DirectoryInfo tempDI = new DirectoryInfo(file);
						tempDI.Delete(true);
					}else{
						File.Delete(file);
					}
				}
			}
		}else{
			DirectoryInfo di3 = new DirectoryInfo(oldPath);
			di3.Delete(true);
		}
	}

    public static void UpdateAndroidSettings()
    {
    //     PlayerPrefs.DeleteAll();
    //    EditorPrefs.DeleteAll();
        UpdateSetting("AndroidSdkRoot", "ANDROID_SDK", "K:/Unity 2020.3.33f1/Editor/Data/PlaybackEngines/AndroidPlayer/SDK", "/Applications/android-sdk-macosx");
        UpdateSetting("AndroidNdkRoot", "ANDROID_NDK", "K:/Unity/Editor/Data/PlaybackEngines/AndroidPlayer/NDK", "/Applications/android-ndk-r13b");
        UpdateSetting("JdkPath", "JAVA_SDK", "K:/Unity 2020.3.33f1/Editor/Data/PlaybackEngines/AndroidPlayer/OpenJDK", "/Library/Java/JavaVirtualMachines/jdk1.8.0_74.jdk/Contents/Home/");
    }

    private static void UpdateSetting(string key, string environmentKey, string defaultWindowsPath, string defaultMacOSPath)
    {
        string environmentPath = Environment.GetEnvironmentVariable(environmentKey);
        if (!string.IsNullOrEmpty(environmentPath) && Directory.Exists(environmentPath))
        {
            EditorPrefs.SetString(key, environmentPath);
            return;
        }

        string defaultPath = Application.platform == RuntimePlatform.WindowsEditor ? defaultWindowsPath : defaultMacOSPath;
        if (!string.IsNullOrEmpty(defaultPath) && Directory.Exists(defaultPath))
        {
            EditorPrefs.SetString(key, defaultPath);
            return;
        }

        throw new DirectoryNotFoundException(string.Format("{0} {1} {2}", key, environmentKey, defaultPath));
    }

    
    public static void DeleteDirectory(string deletePath)
	{
       	string[] files = Directory.GetFiles(deletePath, "*.*", SearchOption.AllDirectories);

		string tempStr1 = "";
		string tempStr3 = "";
		bool haveSVN = false;//是否有SVN 文件
		foreach (string file in files)
		{
			if(!file.Contains(".svn")){
				FileInfo mFile = new FileInfo(file);
				
				if((mFile.Attributes & FileAttributes.Directory) != 0){
					if (!Directory.Exists(file)){
						DeleteDirectory(file);
					}
				}else{
					if(File.Exists(file))
					{
						File.Delete(file);
					}
				}

			
			}
		}
		
		

     
	}

     public static void CopyFolder(string srcPath, string tarPath){
        if(srcPath.Contains(".svn")){
            return;
        }

        
        if (!Directory.Exists(srcPath)){
            UnityEngine.Debug.Log("CopyFolder is finish.");
            return;
        }
        if (!Directory.Exists(tarPath))
        {
            Directory.CreateDirectory(tarPath);
        }

        List<string> files = new List<string>(Directory.GetFiles(srcPath));
        files.ForEach(f =>
        {
            string destFile = Path.Combine(tarPath, Path.GetFileName(f));
            if(destFile.Contains(".svn")){
                
            }else{
                File.Copy(f, destFile, true); //覆盖模式
            }


        
        });
        List<string> folders = new List<string>(Directory.GetDirectories(srcPath));
        folders.ForEach(f =>
        {
            string destDir = Path.Combine(tarPath, Path.GetFileName(f));
            if(destDir.Contains(".svn")){
            
            }else{
                CopyFolder(f, destDir); //递归实现子文件夹拷贝
            }
            
        });
    }
}
